package alibaba.select.order;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.text.Editable;
import android.text.TextWatcher;

public class MainActivity extends Activity {
    
    private TextView statusTextView;
    private Button configButton;
    private Button runButton;
    private EditText orderCountEditText;
    
    private static final String TARGET_PACKAGE = "com.alibaba.wireless";
    
    private static final String PREFS_NAME = "OrderSelectPrefs";
    private static final String KEY_ORDER_COUNT = "orderCount";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 创建布局
        setContentView(createLayout());

        // 设置按钮点击事件
        configButton.setOnClickListener((v) -> openAccessibilitySettings());
        
        // 设置运行按钮点击事件
        runButton.setOnClickListener((v) -> runTargetApplication());
        
        // 加载保存的订单数量
        loadOrderCount();
    }
    
    /**
     * 保存订单数量到SharedPreferences
     */
    private void saveOrderCount(int count) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(KEY_ORDER_COUNT, count);
        editor.apply();
    }
    
    /**
     * 从SharedPreferences加载订单数量
     */
    private void loadOrderCount() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        int count = settings.getInt(KEY_ORDER_COUNT, 1); // 默认值为1
        orderCountEditText.setText(String.valueOf(count));
    }
    
    /**
     * 强制关闭并重新启动目标应用
     */
    private void runTargetApplication() {
        // 检查辅助功能是否已开启
        if (!isAccessibilityServiceEnabled()) {
            Toast.makeText(this, "请先开启辅助功能", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 获取输入框中的订单数量
        String countText = orderCountEditText.getText().toString().trim();
        int orderCount = 1; // 默认值
        
        try {
            orderCount = Integer.parseInt(countText);
            if (orderCount <= 0) {
                orderCount = 1;
                Toast.makeText(this, "订单数量必须大于0，已设置为默认值1", Toast.LENGTH_SHORT).show();
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "无效的订单数量，已设置为默认值1", Toast.LENGTH_SHORT).show();
        }
        
        // 设置要选中的订单数量
        MainService.setOrderSelectCount(orderCount);
        
        // 重置MainService中的点击状态
        MainService.resetClickState();
        
        // 强制关闭目标应用
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        am.killBackgroundProcesses(TARGET_PACKAGE);
        
        // 等待一小段时间确保应用已关闭
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // 启动目标应用
        PackageManager packageManager = getPackageManager();
        Intent launchIntent = packageManager.getLaunchIntentForPackage(TARGET_PACKAGE);
        
        if (launchIntent != null) {
            // 清除之前的任务栈，确保从首页启动
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(launchIntent);
            Toast.makeText(this, "已启动应用，将选择 " + orderCount + " 个订单", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "找不到目标应用：" + TARGET_PACKAGE, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 更新辅助功能状态显示
        updateAccessibilityStatus();
    }
    
    /**
     * 检查辅助功能服务是否启用
     */
    private boolean isAccessibilityServiceEnabled() {
        String serviceName = getPackageName() + "/" + MainService.class.getCanonicalName();
        String enabledServices = Settings.Secure.getString(
                getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        
        return enabledServices != null && enabledServices.contains(serviceName);
    }
    
    /**
     * 更新辅助功能状态显示
     */
    private void updateAccessibilityStatus() {
        boolean isEnabled = isAccessibilityServiceEnabled();
        if (isEnabled) {
            statusTextView.setText("辅助功能状态：已开启");
            statusTextView.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
            // 当辅助功能已开启时，禁用配置按钮
            configButton.setEnabled(false);
            configButton.setText("辅助功能已开启");
        } else {
            statusTextView.setText("辅助功能状态：未开启");
            statusTextView.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
            // 当辅助功能未开启时，启用配置按钮
            configButton.setEnabled(true);
            configButton.setText("去配置辅助功能");
        }
    }
    
    /**
     * 打开辅助功能设置页面，直接导航到当前应用的辅助功能设置
     */
    private void openAccessibilitySettings() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        
        // 尝试直接导航到当前应用的辅助功能设置页面
        String packageName = getPackageName();
        String componentName = packageName + "/" + MainService.class.getCanonicalName();
        
        // 方法1：使用组件名称作为fragment参数
        intent.putExtra(":settings:fragment_args_key", componentName);
        intent.putExtra(":settings:show_fragment_args", true);
        
        // 方法2：使用额外数据指向特定服务
        intent.setData(Uri.parse("package:" + packageName));
        
        try {
            startActivity(intent);
        } catch (Exception e) {
            // 如果直接导航失败，回退到标准辅助功能设置页面
            intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivity(intent);
        }
    }
    
    /**
     * 创建布局
     */
    private View createLayout() {
        // 这里简化处理，实际应该使用XML布局文件
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(16, 16, 16, 16);
        
        // 创建状态文本视图
        statusTextView = new TextView(this);
        statusTextView.setId(View.generateViewId());
        statusTextView.setTextSize(18);
        LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        textParams.setMargins(0, 0, 0, 32);
        statusTextView.setLayoutParams(textParams);
        
        // 创建配置按钮
        configButton = new Button(this);
        configButton.setId(View.generateViewId());
        configButton.setText("配置辅助功能");
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        configButton.setLayoutParams(buttonParams);
        
        // 创建订单数量输入框
        LinearLayout orderCountLayout = new LinearLayout(this);
        orderCountLayout.setOrientation(LinearLayout.HORIZONTAL);
        orderCountLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
        orderCountLayout.setVerticalGravity(android.view.Gravity.CENTER_VERTICAL);
        
        TextView orderCountLabel = new TextView(this);
        orderCountLabel.setText("选择订单数量: ");
        orderCountLabel.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
        
        // 减少按钮
        Button decreaseButton = new Button(this);
        decreaseButton.setText("-");
        decreaseButton.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        decreaseButton.setOnClickListener(v -> {
            try {
                int currentCount = Integer.parseInt(orderCountEditText.getText().toString());
                if (currentCount > 1) {
                    currentCount--;
                    orderCountEditText.setText(String.valueOf(currentCount));
                    saveOrderCount(currentCount);
                }
            } catch (NumberFormatException e) {
                orderCountEditText.setText("1");
                saveOrderCount(1);
            }
        });
        
        orderCountEditText = new EditText(this);
        orderCountEditText.setId(View.generateViewId());
        orderCountEditText.setText("1");
        orderCountEditText.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);
        orderCountEditText.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1));
        orderCountEditText.setMinWidth(100);
        orderCountEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    try {
                        int count = Integer.parseInt(s.toString());
                        saveOrderCount(count);
                    } catch (NumberFormatException e) {
                        // 如果输入不是有效数字，不保存
                    }
                }
            }
        });
        
        // 增加按钮
        Button increaseButton = new Button(this);
        increaseButton.setText("+");
        increaseButton.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        increaseButton.setOnClickListener(v -> {
            try {
                int currentCount = Integer.parseInt(orderCountEditText.getText().toString());
                currentCount++;
                orderCountEditText.setText(String.valueOf(currentCount));
                saveOrderCount(currentCount);
            } catch (NumberFormatException e) {
                orderCountEditText.setText("1");
                saveOrderCount(1);
            }
        });
        
        orderCountLayout.addView(orderCountLabel);
        orderCountLayout.addView(decreaseButton);
        orderCountLayout.addView(orderCountEditText);
        orderCountLayout.addView(increaseButton);
        
        // 创建运行按钮
        runButton = new Button(this);
        runButton.setId(View.generateViewId());
        runButton.setText("运行");
        LinearLayout.LayoutParams runButtonParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        runButtonParams.setMargins(0, 16, 0, 0);  // 添加顶部间距
        runButton.setLayoutParams(runButtonParams);
        
        // 添加视图到布局
        layout.addView(statusTextView);
        layout.addView(configButton);
        layout.addView(orderCountLayout);
        layout.addView(runButton);
        layout.setKeepScreenOn(true);
        return layout;
    }
}